<?php


class Dispatcher {
    
    /**
     * @return   void
     */
    public function dispatch() {
        $webroot = preg_replace('#/[^/]+$#', '', $_SERVER['SCRIPT_NAME']);
        $router = Router::getInstance();
        $q      = trim(isset($_GET['q'])?$_GET['q']:'');
        $params = $router->parse(str_replace(array('-',PREFIX,'.ps','.html','.mk'), '/', $q));
        
        if(count($_GET) > 1){
            unset($_GET['q']);
            foreach ($_GET as $k => $v) {
                $params[$k] = $v;
            }
        }

        $request = Request::getInstance();
        $request->setParams($params);
        $request->setParams($webroot, 'webroot');
        $module_class = $params['module'].'Action';
        $str_len      = strlen($params['module']);
        if (!class_exists($module_class) && $str_len!=6) {
            Request::getInstance()->render404();
        }elseif($str_len == 6 &&!class_exists($module_class)){
            $module_class   = 'homeAction';
            $params['module']   = 'home';
            $params['action']   = 'go';
            $request->setParams($params);
        }

        $module = new $module_class;
        
        $module->setParams($params);
        $module->setView(new PhpView());
        $module->getView()->webroot = $webroot;
        
        $module->execute();
    }
}
